package com.crm.miaohe.service;

import com.crm.miaohe.controller.report.response.OrderReportYear;
import com.crm.miaohe.mapper.TblOrderMapper;
import com.crm.miaohe.model.TblOrder;
import com.crm.miaohe.model.TblOrderExample;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("yearOrderReportService")
public class OrderYearReportService implements OrderReportService<OrderReportYear> {

    private TblOrderMapper tblOrderMapper;

    public OrderYearReportService(TblOrderMapper tblOrderMapper) {
        this.tblOrderMapper = tblOrderMapper;
    }

    @Override
    public OrderReportYear orderReport() {
        LocalDate firstDayOfYear = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
        TblOrderExample orderExample = new TblOrderExample();
        orderExample.createCriteria().andCreateTimeGreaterThanOrEqualTo(firstDayOfYear.atStartOfDay()).andCreateTimeLessThan(firstDayOfYear.with(TemporalAdjusters.firstDayOfNextYear()).atStartOfDay()).andStatusEqualTo(1);

        List<Map.Entry<YearMonth, List<TblOrder>>> entries = tblOrderMapper.selectByExample(orderExample)
                .stream().collect(Collectors.groupingBy(tblOrder -> YearMonth.of(tblOrder.getCreateTime().getYear(), tblOrder.getCreateTime().getMonth())))
                .entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());

        int monthOfYear = 0, index = 0, size = entries.size();
        YearMonth firstMonth = YearMonth.of(firstDayOfYear.getYear(), firstDayOfYear.getMonth());
        OrderReportYear history = new OrderReportYear(firstDayOfYear.getYear(), 12);
        while (index < size && monthOfYear < 12) {
            YearMonth month = firstMonth.plusMonths(monthOfYear);
            Map.Entry<YearMonth, List<TblOrder>> entry = entries.get(index);
            if (month.equals(entry.getKey())) {
                history.getAlertHistory().add(BigInteger.valueOf(entry.getValue().size()));
                index++;
            } else {
                history.getAlertHistory().add(BigInteger.ZERO);
            }
            monthOfYear++;
        }
        List<BigInteger> historyData = history.getAlertHistory();
        while (historyData.size() < 12) {
            historyData.add(BigInteger.ZERO);
        }
        return history;
    }
}
